<template>
  <div style="display: flex;">
    <div style="flex: 1; display: flex; flex-direction: column;">
      <template>
        <el-carousel height="150px">
          <el-carousel-item v-for="item in advertisingList" :key="item">
            <img :src="item.advicePic" alt="shop image" style="width: 100%; height: 350px; object-fit: cover;" />
            <div style="padding: 14px 0;">
              <h3>{{ item.message }}</h3>
            </div>
          </el-carousel-item>
        </el-carousel>
      </template>


      <el-row :gutter="20" style="flex-grow: 1; overflow-y: auto;">
        <el-col v-for="shop in merchantList" :key="shop.id" :span="6">
          <el-card :body-style="{ padding: '20px' }">
            <img :src="shop.picture" alt="shop image" style="width: 100%; height: 350px; object-fit: cover;" />
            <div style="padding: 14px 0;">
              <h3>{{ shop.merchantName }}</h3>
              <p>{{ shop.address }}</p>
            </div>
            <el-button type="primary"  @click="handleViewDetail(shop)">查看详情</el-button>
          </el-card>
        </el-col>
      </el-row>







      <div style="margin-top: 500px;text-align: center;">
        <el-pagination
          background
          popper-class="select-box-body"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, sizes"
          :total="total"
        >
        </el-pagination>
      </div>

    </div>

    <div style="width: 300px; margin-left: 20px;">
      <h2>店铺推荐</h2>
      <el-card title="推荐店铺" :body-style="{ padding: '10px' }">
        <el-list>
          <el-list-item
            v-for="recommendedShop in recommendedShops"
            :key="recommendedShop.id"
            style="display: flex; align-items: inherit;padding-bottom: 20px">
            <img :src="recommendedShop.picture" alt="recommended shop" style="width: 60px; height: 60px; object-fit: cover; margin-right: 10px;" />
            <div>
              <h4>{{ recommendedShop.merchantName }}</h4>
              <p>{{ recommendedShop.description }}</p>
            </div>
            <el-button size="mini" type="text" icon="el-icon-folder-opened" @click="handleViewDetail(recommendedShop)"
                       v-hasPermi="['system:notice:query']">详情</el-button>
          </el-list-item>
          <div></div>
        </el-list>
      </el-card>
    </div>



  </div>
</template>

<script>
import {listMerchant} from "@/api/system/merchant";
import {addRecord, listRecord} from "@/api/system/record";
import {getUserProfile} from "@/api/system/user";
import {
  getSetting
} from "@/api/system/setting";
import {
  listMessage
} from "@/api/system/message";
import advertising from "@/views/system/advertising/index.vue";
import {listAdvertising} from "@/api/system/advertising";


export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 2,
      total:0,
      merchantList: [],
      queryBehaviorParams: {
        pageNum: 1,
        pageSize: 10,
        cusId: null,
        cusName: null,
        businessCuisine: null,
        businessStore: null,
        behaviorType: null,
        storeStyle: null
      },
      queryMessageParams: {
        pageNum: 1,
        pageSize: 10,
        merchantId: ''
      },
      queryParams: {

      },
      adverseParams:{

      },
      advertisingList:[],
      shops: [
        { id: 1, name: '店铺A', description: '这是店铺A的描述。', image: 'https://via.placeholder.com/300' },
        { id: 2, name: '店铺B', description: '这是店铺B的描述。', image: 'https://via.placeholder.com/300' },
        { id: 3, name: '店铺C', description: '这是店铺C的描述。', image: 'https://via.placeholder.com/300' },
        { id: 4, name: '店铺D', description: '这是店铺D的描述。', image: 'https://via.placeholder.com/300' },
        { id: 5, name: '店铺E', description: '这是店铺E的描述。', image: 'https://via.placeholder.com/300' },
        { id: 6, name: '店铺F', description: '这是店铺F的描述。', image: 'https://via.placeholder.com/300' },
        { id: 7, name: '店铺G', description: '这是店铺G的描述。', image: 'https://via.placeholder.com/300' },
        { id: 8, name: '店铺H', description: '这是店铺H的描述。', image: 'https://via.placeholder.com/300' }
      ],
      recommendedShops: []
    };
  },
  computed: {

    paginatedShops() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.shops.slice(start, end);
    }
  },
  mounted() {
    getSetting(1).then(response =>{
      console.log(response)
      this.styleWeight = response.data.styleWeight;
      this.evaluateWeight = response.data.evaluateWeight;
      this.getList();
      this.advertising();
    });
  },
  methods: {
    advertising() {
      this.adverseParams.useStatus = 0;
      listAdvertising(this.adverseParams).then(response =>{
        console.log("广告"+JSON.stringify(response))
          for (let i = 0; i < response.rows.length; i++) {
            let merchantListTemp = response.rows[i];
            if (merchantListTemp.advicePic.length > 0) {
              response.rows[i].advicePic = process.env.VUE_APP_BASE_API + merchantListTemp.advicePic
            } else {
              response.rows[i].advicePic = '/errorImg.jpg'
            }
          }
        this.advertisingList = response.rows;
        console.log("广告"+JSON.stringify(this.advertisingList))
      })
    },
    getList() {
      this.loading = true;
      console.log("查询店铺")
      listMerchant(this.queryParams).then(async response => {

        for (let i = 0; i < response.rows.length; i++) {
          let merchantListTemp = response.rows[i];
          if (merchantListTemp.picture.length > 0) {
            response.rows[i].picture = process.env.VUE_APP_BASE_API + merchantListTemp.picture
          }else{
            response.rows[i].picture = '/errorImg.jpg'
          }
          //获取权重
          let queryNum = 0;
          let rateAvg = 0;
          await getUserProfile().then(async response =>{
            this.queryBehaviorParams.cusName = response.data.userName;
            this.queryBehaviorParams.businessStore = merchantListTemp.merchantName;
            await listRecord(this.queryBehaviorParams).then(async response =>{
              //根据行为对每个店铺进行权重计算，根据权重进行排序
              queryNum = response.total; //浏览该店铺的次数
              //获取评分
              this.queryMessageParams.merchantId = merchantListTemp.merchantId;
              await listMessage(this.queryMessageParams).then(response =>{
                console.log("list---"+JSON.stringify(response))
                this.list = response.rows;
                let sum = 0;
                if(this.list.length > 0){
                  for (let j = 0; j < this.list.length; j++) {
                    sum += parseInt(this.list[j].rating);
                  }
                  rateAvg = sum/this.list.length;
                }
                console.log("rateAvg---"+sum +"======="+ this.list.length +"===="+rateAvg)
              });
            });
          });
          console.log("第"+i+"条数据queryNum---"+queryNum)
          console.log("第"+i+"条数据rateAvg---"+rateAvg)
          console.log("权重= "+queryNum * this.styleWeight +  rateAvg * this.evaluateWeight)
          response.rows[i].storeWeightSetting = queryNum * this.styleWeight +  rateAvg * this.evaluateWeight;
        };
        //排序
        this.merchantList = response.rows;
        let tempList = response.rows.slice();
        let len = tempList.length;
        for (let i = 0; i < len - 1; i++) {
          for (let j = 0; j < len - 1 - i; j++) {
            if (parseFloat(tempList[j].storeWeightSetting) > parseFloat(tempList[j + 1].storeWeightSetting)) {        // 相邻元素两两对比
              [tempList[j], tempList[j + 1]] = [tempList[j + 1], tempList[j]]; // 元素交换
            }
          }
        }

        this.recommendedShops = tempList;
        console.log("商家=-=="+JSON.stringify(response));
        this.total = response.total;
      });
      this.loading = false;
    },
    handleCurrentChange(page) {
      this.currentPage = page;
    },
    handleSizeChange(newSize) {
      this.currentPage = newSize;  // 更新当前的 pageSize
    },
    handleViewDetail(shop) {
        console.log(shop.id);
      // 跳转到店铺详情页面
      //记录行为
      getUserProfile().then(response =>{
        console.log("当前用户信息"+JSON.stringify(response))
        const params = {
          // id: null,
          cusId: response.data.userId,
          cusName: response.data.userName,
          businessCuisine: null,
          businessStore: shop.merchantName,
          behaviorType: '1',//浏览
          storeStyle: shop.tone,
        };
        addRecord(params).then(response => {
          console.log("行为记录");
        });

        // 这里只是简单的跳转到 /cms/merchant/1 页面
        let routeUrl = this.$router.resolve({
          path: '/cms/main/merchantDetail',
          query: {
            id: shop.id
          }
        });
        window.open(routeUrl.href, '_self');
        // 实际项目中，应该根据实际情况进行调整
      });
    }
  }
};
</script>

<style scoped>
/* 你可以添加一些自定义样式 */
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
  text-align: center;
}
</style>
